package com.ucap.wsbs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.ucap.util.*;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.*;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2018/5/14.
 */
public class FileController extends Controller {
    public void upload() {
        try {
            String uploadPath = Conts.getSessionUser(getSession()).get("id").toString() + "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay();
            UploadFile file = getFile("file", uploadPath);
            WxWsbsFile wsbsFile = new WxWsbsFile();
            wsbsFile.set("ID", StringUtils.getUUID());
            wsbsFile.set("SBLSH", Conts.getWsbsSblsh(getSession()));
            wsbsFile.set("USERID", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("FILEPATH", "/files/upload/" + uploadPath + "/" + file.getFileName());
            wsbsFile.set("FILENAME", file.getFileName());
            wsbsFile.set("CONTENTTYPE", file.getContentType());
            wsbsFile.set("TABLENAME", getPara("tableName"));
            wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
            wsbsFile.set("ADDUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
            wsbsFile.set("UPDATEUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("DATASTATE", "I");

            JSONObject msg = new JSONObject();
            try {
                boolean boo = wsbsFile.save();
                msg.put("success", boo);
                if (boo) {
                    msg.put("msg", "上传材料成功");
                } else {

                    msg.put("msg", "上传材料失败");
                }
                msg.put("data", wsbsFile);
            } catch (Exception e) {
                msg.put("success", false);
                msg.put("msg", "上传材料失败");
                e.printStackTrace();
            }

            renderJson(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void query() {
        List paras = new ArrayList();


        if (!StringUtils.isEmpty(getPara("tableName"))) {
            paras.add(getPara("tableName"));
        }
        if (!StringUtils.isEmpty(Conts.getWsbsSblsh(getSession()))) {
            paras.add(Conts.getWsbsSblsh(getSession()));
        }
        List<WxWsbsFile> fileList = WxWsbsFile.me.findFileListByTableName(paras);
;        System.out.println("材料数量" + fileList.size());
        JSONObject msg = new JSONObject();
        try {
            msg.put("data", fileList);
            msg.put("success", true);
        } catch (Exception e) {
            msg.put("success", false);
            e.printStackTrace();
        }

        renderJson(msg);
    }

    public void del() {
        WxWsbsFile file = new WxWsbsFile();
        JSONObject msg = new JSONObject();
        if (!StringUtils.isEmpty(getPara("id"))) {
            file.set("id", getPara("id"));
            boolean boo = file.delete();
            msg.put("success", boo);
            if (boo) {
                msg.put("msg", "删除材料成功");
            } else {
                msg.put("msg", "删除材料失败");
            }
        }
        renderJson(msg);
    }

    public void createSbxxFile() {


    }

    private JSONObject getCheck(String sbxx,String jyxmlx) {
        System.out.println(sbxx.toString());
        JSONArray array = JSONArray.parseArray(sbxx);
        JSONObject ytlx = new JSONObject();
        for (Object item : array) {
            JSONObject json = JSONObject.parseObject(item.toString());
            if((json.get("title").toString().contains("其他类食品销售")&&jyxmlx.contains("其他类食品销售"))||(json.get("title").toString().contains("其他类食品制售")&&jyxmlx.contains("其他类食品制售"))){
                System.out.println(json.get("name").toString());
                ytlx.put(json.get("name").toString(), "1");
                ytlx.put(json.get("name").toString()+"_jtpz", json.get("value"));
            }else  if((json.get("title").toString().contains("热食类食品制售")&&jyxmlx.contains("热食类食品制售"))||(json.get("title").toString().contains("生食类食品制售")&&jyxmlx.contains("生食类食品制售"))||(json.get("title").toString().contains("食品经营管理")&&jyxmlx.contains("食品经营管理"))){
                System.out.println(json.get("name").toString());
                ytlx.put(json.get("name").toString(), "1");
            }else if (!StringUtils.isEmpty(json.getString("value"))) {
                ytlx.put(json.get("name").toString(), "1");
                for (Object itemt : array) {
                    JSONObject jsont = JSONObject.parseObject(itemt.toString());
                    if (json.get("value").equals(jsont.get("title")) || ("qtlspxx").equals(jsont.get("name"))) {
                        ytlx.put(jsont.get("name").toString(), "1");
                        if (("qtlspxx").equals(jsont.get("name").toString())){
                            ytlx.put(jsont.get("name").toString(), jsont.get("value")==null?"":jsont.get("value").toString());
                        }
                    }
                }
            }else{

                if(ytlx.get(json.get("name"))==null){
                    ytlx.put(json.get("name").toString(), "0");
                }
            }
        }
        return ytlx;
    }

    /**
     * 下载图片
     */
    public void downloadImage()
    {
        String sblsh = getPara("sblsh");
        String tableName = getPara("tableName");
        List paras = new ArrayList();
        if (!StringUtils.isEmpty(tableName)){
            paras.add(tableName);
        }
        if (!StringUtils.isEmpty(sblsh)){
            paras.add(sblsh);
        }
        List<WxWsbsFile> tjctInfo = WxWsbsFile.me.findFileListBysblshAndTableName(paras);
        try {
            String rootPath = PathKit.getWebRootPath();
            String tmpFileName = sblsh + ".zip";
            String zipfilePath = rootPath+"\\files\\"+tmpFileName;
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfilePath));
            int index = 0;
            for (WxWsbsFile p:tjctInfo)
            {
                byte[] buffer = new byte[1024];
                String filePath = rootPath + p.getStr("FILEPATH");
                FileInputStream fis = new FileInputStream(new File(filePath));
                String types = p.getStr("FILENAME");
                String type = types.split("\\.")[1];
                out.putNextEntry(new ZipEntry(p.getStr("FILENAME") + "_" + index + "." + type));
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) > 0)
                {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
                index++;
            }
            out.close();
            this.downloadFile(zipfilePath, this.getResponse(), tmpFileName);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public void downloadFile(String filePath, HttpServletResponse response, String tmpFileName)
    {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + tmpFileName);
        try
        {
            // 创建文件
            File file = new File(filePath);
            InputStream inputStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
            inputStream.close();
            file.delete(); // 将生成的服务器端文件删除
            os.flush(); //
            os.close();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 预览图片
     */
    public void showImgs()
    {
        String userId = getPara("USERID");
        String sblsh = getPara("SBLSH");
        String tablename = getPara("TABLENAME");
        List paras = new ArrayList();
        if (!StringUtils.isEmpty(sblsh)){
            paras.add(sblsh);
        }
        if (!StringUtils.isEmpty(tablename)){
            paras.add(tablename);
        }

        JSONArray jsonArray = new JSONArray();
        String rootPath = PathKit.getWebRootPath();
        List<WxWsbsFile> tjctInfo = WxWsbsFile.me.findClsbyUIDandSBLSHandTbName(paras);
        if(tjctInfo != null){
            for (WxWsbsFile p : tjctInfo) {
                Map<String,String> wFile = new HashMap<String,String>();
                wFile.put("rootPath", rootPath);
                wFile.put("filepath",p.getStr("FILEPATH"));
                wFile.put("fileName",p.getStr("FILENAME"));
                jsonArray.add(wFile);
            }
        }
        String callback=getRequest().getParameter("callback");
        String jsonp = callback + "(" + jsonArray + ")";
        renderJson(jsonp);
    }

    /**
     * 下载word
     * @throws Exception
     */
    public void downloadWord()
    {
        String sblsh = getPara("sblsh");
        List paras = new ArrayList();
        //createFileWord(sblsh);
        if (!StringUtils.isEmpty(sblsh))
        {
            paras.add(sblsh);
            paras.add("dzsqb");
        }
        try
        {
            String rootPath = PathKit.getWebRootPath();
            if(sblsh != null)
            {
                WxWsbsFile tjctInfo = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                if(tjctInfo==null){
                    createFileWord(sblsh);
                    tjctInfo = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                }
                String filePath = rootPath + tjctInfo.getStr("FILEPATH");
                String fileName = sblsh + ".doc";
                FileDownload.fileDownload(this.getResponse(), filePath, fileName);
            }
        }catch (IOException io)
        {
            io.printStackTrace();
            System.out.println("word下载失败");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("word下载失败");
        }
    }



    private WxWsbsFile createFileWord(String sblsh) {
        try {
            /** 初始化配置文件 **/
            Configuration configuration = new Configuration();
            /** 设置编码 **/
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassicCompatible(true);//设置属性
            /** 加载文件 **/
            configuration.setDirectoryForTemplateLoading(new File(PathKit.getWebRootPath() + "/files/download/freemarker/form"));
            /** 加载模板 **/
            Template template = null;
            /** 准备数据 **/
            Map<String, Object> dataMap = new HashMap<>();

            /** 表格数据初始化 **/
            System.out.println(sblsh);
            WxWsbsSbxx sbxx = WxWsbsSbxx.me.findBySblsh(sblsh);

            if(sbxx.getStr("sblx").equals("0")){
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sblsh);
                WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(sblsh);

                sbxx.set("sp_sex", StringFormat.parseNation(sbxx.get("sp_sex").toString()));
                sbxx.set("sp_idtype", StringFormat.parseIdtype(sbxx.get("sp_idtype").toString()));
                sbxx.put("year",sbxx.get("updatetime").toString().substring(0,4));
                sbxx.put("month",sbxx.get("updatetime").toString().substring(5,7));
                sbxx.put("day",sbxx.get("updatetime").toString().substring(8,10));
                sbxx.put("wzdz", StringFormat.parseNull(sbxx.get("wzdz")));
                sbxx.put("wljy", StringFormat.parseNull(sbxx.get("wljy")));
                sbxx.put("stmd", StringFormat.parseNull(sbxx.get("stmd")));
                frxx.set("sex", StringFormat.parseSex(frxx.get("sex").toString()));
                frxx.set("idtype", StringFormat.parseIdtype(frxx.get("idtype").toString()));
                if(frxx.get("tel")==null){
                    frxx.set("tel"," ");
                }
                template = configuration.getTemplate("spjyxuksb.ftl");
                /** 表格数据 studentList和freemarker标签要对应**/
                String jycsdz = qyxx.getStr("jycsdz");
                String live = frxx.getStr("live");
                if(live!=null&&live.indexOf("省")!=-1){
                    frxx.set("live",live.substring(live.indexOf("省")+1,live.indexOf("市")));
                }else{
                    frxx.set("live",StringFormat.parseNull(live));

                }
                frxx.set("detailedlive",StringFormat.parseNull(frxx.getStr("detailedlive")));
                if(jycsdz!=null&&jycsdz.indexOf("省")!=-1&&jycsdz.indexOf("市")!=-1){
                    qyxx.put("jycsdz_shi",jycsdz.substring(jycsdz.indexOf("省")+1,jycsdz.indexOf("市")));
                    qyxx.put("jycsdz_dz",jycsdz.substring(jycsdz.indexOf("市")+1,jycsdz.length()));
                }else{
                    qyxx.put("jycsdz_shi","");
                    qyxx.put("jycsdz_dz",jycsdz);
                }
                System.out.println(sbxx.get("ytlx"));
                System.out.println(sbxx.get("jyxm"));
              /*  dataMap.put("ytlx", getCheck(sbxx.getStr("ytlx"),sbxx.getStr("ztytlx")));
                dataMap.put("jyxm", getCheck(sbxx.getStr("jyxm"),sbxx.getStr("jyxmlx")));*/
                System.out.println(getValue(JSONArray.parseArray(sbxx.get("ytlx").toString())));
                System.out.println(getValue(JSONArray.parseArray(sbxx.get("jyxm").toString())));
                dataMap.put("ytlx",getValue(JSONArray.parseArray(sbxx.get("ytlx").toString())));
                dataMap.put("jyxm", getValue( JSONArray.parseArray(sbxx.get("jyxm").toString())));
                dataMap.put("qyxx", qyxx);
                dataMap.put("frxx", frxx);
                dataMap.put("sbxx", sbxx);
            }else if(sbxx.getStr("sblx").equals("1")){
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sblsh);
                WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(sblsh);

                sbxx.set("sp_sex", StringFormat.parseNation(sbxx.get("sp_sex").toString()));
                sbxx.set("sp_idtype", StringFormat.parseIdtype(sbxx.get("sp_idtype").toString()));
                sbxx.put("year",sbxx.get("updatetime").toString().substring(0,4));
                sbxx.put("month",sbxx.get("updatetime").toString().substring(5,7));
                sbxx.put("day",sbxx.get("updatetime").toString().substring(8,10));
                sbxx.put("wzdz", StringFormat.parseNull(sbxx.get("wzdz")));
                sbxx.put("wljy", StringFormat.parseNull(sbxx.get("wljy")));
                sbxx.put("stmd", StringFormat.parseNull(sbxx.get("stmd")));
                frxx.set("sex", StringFormat.parseSex(frxx.get("sex").toString()));
                frxx.set("idtype", StringFormat.parseIdtype(frxx.get("idtype").toString()));
                if(frxx.get("tel")==null){
                    frxx.set("tel"," ");
                }
                template = configuration.getTemplate("xbsqb.ftl");

                dataMap.put("ytlx",getValue(JSONArray.parseArray(sbxx.get("ytlx").toString())));
                dataMap.put("jyxm", getValue( JSONArray.parseArray(sbxx.get("jyxm").toString())));
                dataMap.put("qyxx", qyxx);
                dataMap.put("frxx", frxx);
                dataMap.put("sbxx", sbxx);
            }else if(sbxx.getStr("sblx").equals("2")){
                sbxx.put("year",sbxx.get("updatetime").toString().substring(0,4));
                sbxx.put("month",sbxx.get("updatetime").toString().substring(5,7));
                sbxx.put("day",sbxx.get("updatetime").toString().substring(8,10));
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sbxx.getStr("ysblsh"));
                WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(sbxx.getStr("ysblsh"));
                dataMap.put("qyxx", qyxx);
                dataMap.put("frxx", frxx);
                dataMap.put("sbxx", sbxx);
                template = configuration.getTemplate("bgyxsqb.ftl");
            }else if(sbxx.getStr("sblx").equals("3")){
                sbxx.put("year",sbxx.get("updatetime").toString().substring(0,4));
                sbxx.put("month",sbxx.get("updatetime").toString().substring(5,7));
                sbxx.put("day",sbxx.get("updatetime").toString().substring(8,10));
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sbxx.getStr("sblsh"));
                WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(sbxx.getStr("sblsh"));
                dataMap.put("qyxx", qyxx);
                dataMap.put("frxx", frxx);
                dataMap.put("sbxx", sbxx);
                template = configuration.getTemplate("bgyxsqb.ftl");
            }else if(sbxx.getStr("sblx").equals("4")){
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sbxx.getStr("ysblsh"));
                dataMap.put("qyxx", qyxx);
                dataMap.put("sbxx", sbxx);
                template = configuration.getTemplate("bzzxsqb.ftl");
            }else if(sbxx.getStr("sblx").equals("5")){
                WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(sbxx.getStr("ysblsh"));
                dataMap.put("qyxx", qyxx);
                dataMap.put("sbxx", sbxx);
                template = configuration.getTemplate("bzzxsqb.ftl");
            }



            /** 指定输出word文件的路径 **/
            String uploadPath = "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay()+"/" +sblsh;

            String filePth = "/files/upload/" + uploadPath + "/" + sblsh + ".doc";
            File docFile = new File(PathKit.getWebRootPath() + filePth);
            if (!docFile.getParentFile().exists()) {
                docFile.getParentFile().mkdirs();//不存在则创建父目录
                docFile.createNewFile();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile), "UTF-8"));
           // isNullOrEmpty(dataMap);
            template.process(dataMap, out);

            WxWsbsFile wsbsFile = new WxWsbsFile();
            wsbsFile.set("ID", StringUtils.getUUID());
            wsbsFile.set("SBLSH",sblsh);
            wsbsFile.set("USERID", sblsh);
            wsbsFile.set("FILEPATH", filePth);
            wsbsFile.set("FILENAME", sblsh + ".doc");
            wsbsFile.set("CONTENTTYPE", "application/msword");
            wsbsFile.set("TABLENAME", "dzsqb");
            wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
            wsbsFile.set("ADDUSER", "系统生成");
            wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
            wsbsFile.set("UPDATEUSER", "系统生成");
            wsbsFile.set("DATASTATE", "I");

            JSONObject msg = new JSONObject();
            try {
                boolean boo = wsbsFile.save();
                msg.put("success", boo);
                if (boo) {

                    msg.put("msg", "上传材料成功");
                    return wsbsFile;
                } else {

                    msg.put("msg", "上传材料失败");
                }
                msg.put("data", wsbsFile);
            } catch (Exception e) {
                msg.put("success", false);
                msg.put("msg", "上传材料失败");
                e.printStackTrace();
            }


            if (out != null) {
                out.close();
            }
            renderJson(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject getValue(JSONArray ytlx) {
        JSONObject val=new JSONObject();
        for (int i=0;i<ytlx.size();i++){
            JSONObject item= (JSONObject)ytlx.get(i);
               val.put(item.getString("name"),item.getString("value"));
        }
        return val;
    }

    private void isNullOrEmpty(Map<String, Object> dataMap) throws IllegalAccessException {
       for(Object obj:dataMap.values()){
           checkObjFieldIsNull(obj);
       }
    }
    public  void checkObjFieldIsNull(Object obj) throws IllegalAccessException {

        String flag = "";
        for(Field f : obj.getClass().getDeclaredFields()){
            f.setAccessible(true);

            if(f.get(obj) == null){
                f.set(obj, "");
            }
            System.out.println(obj+"======"+f.get(obj));
        }

    }
}
